/**
 * 
 */
package it.agm.fanta.asynctask;



import it.agm.activity.dialog.GenericDialog;
import it.agm.fanta.FantaserviceApp;
import it.agm.fanta.R;
import it.agm.fanta.activity.LoginActivity;
import it.agm.fanta.asynctask.jersey.patch.AndroidServiceIteratorProvider;
import it.agm.fanta.asynctask.jersey.patch.MIMETypes;
import it.agm.fanta.constants.Constants;
import it.agm.fanta.exception.ConnectionException;
import it.agm.fanta.model.LegaSquadra;
import it.agm.fanta.model.Utente;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;

import android.app.Activity;
import android.app.Dialog;
import android.app.backup.BackupManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.spi.service.ServiceFinder;

/**
 * @author AGM
 * 
 */
public class UserLoginTask extends SyncAsyncTask {

	private boolean rimaniConnesso;
	
	private Intent intent;
	private boolean isLegaPresent = false;
	
	@SuppressWarnings("rawtypes")
	public UserLoginTask(Context context, LoginActivity main, Intent intent,
			boolean rimaniConnesso) {
		ServiceFinder.setIteratorProvider(new AndroidServiceIteratorProvider());
		this.context = context;
		this.intent = intent;
		this.rimaniConnesso = rimaniConnesso;
		meinActivityWeakRef = new WeakReference<LoginActivity>(main);
	}

	@Override
	protected void onPreExecute() {

	}

	@Override
	protected void onPostExecute(Void result) {
		super.onPostExecute(result);
		
		if(FantaserviceApp.utente != null){
			if(!isLegaPresent){
				mdialog = new Dialog(meinActivityWeakRef.get());
				mdialog.setContentView(R.layout.dialog_alert);
				TextView mTitle = (TextView) mdialog.findViewById(R.id.alert_message);
				mdialog.setTitle("ATTENZIONE");
				
				mTitle.setText(context.getResources().getString(R.string.alert_mancanza_lega));
				View mTitleDivider = mdialog.findViewById(Resources.getSystem().getIdentifier("titleDivider", "id", "android"));
				mTitleDivider.setBackgroundColor(meinActivityWeakRef.get().getResources().getColor(R.color.black));
				Button mbutton = (Button) mdialog.findViewById(R.id.alert_buttom);
				mbutton.setOnClickListener(new OnClickListener() {
			        @Override
					public void onClick(View v) {
						if (UserLoginTask.this.mdialog != null) {
							UserLoginTask.this.mdialog.dismiss();
						}
						intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
						context.startActivity(intent);
						meinActivityWeakRef.get().finish();
					}
			      });
				mdialog.setCancelable(true);
				mdialog.show();
			}else{
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				context.startActivity(intent);
				meinActivityWeakRef.get().finish();
			}
		}else{
			intent = new Intent(meinActivityWeakRef.get(), LoginActivity.class);
			meinActivityWeakRef.get().runOnUiThread(new Runnable(){
	            public void run() {
	            	new GenericDialog(meinActivityWeakRef.get(), "Login Errato",Constants.TITLE_ERROR);
//	            	LoginActivity login =
	            	meinActivityWeakRef.get().showProgress(false);
	                }
	    	});
		}
		
	}


	@Override
	protected Void doInBackground(Void... params) {
		ObjectMapper mapper = new ObjectMapper();
		try {
			setData(mapper);
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ConnectionException e) {
			FantaserviceApp.utente = null;
			final String msg = e.getMessage();
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			context.startActivity(intent);
			meinActivityWeakRef.get().finish();
			try {
			    Thread.sleep(3000);                 //1000 milliseconds is one second.
			} catch(InterruptedException ex) {
			    Thread.currentThread().interrupt();
			}
			FantaserviceApp.currentActivity().runOnUiThread(new Runnable() {
				public void run() {
					
					new GenericDialog(FantaserviceApp.currentActivity(), context
							.getResources()
							.getString(R.string.alert_connection) + " Codice : " + msg, "WARN");
				}
			});
			
		}

		return null;
	}
	/**
	 * @throws ConnectionException 
	 * 
	 */
	public boolean setData(ObjectMapper mapper) throws JSONException,
			UnsupportedEncodingException, IOException, ClientProtocolException,
			JsonParseException, JsonMappingException, ConnectionException {
		boolean retVal = false;
		Utente[] utenti = null;
		
		final Gson gson = new GsonBuilder().create();
		final Client client = Client.create();
		final WebResource resource = client.resource(Constants.URL_REST + Constants.SERVICE_LOGIN);
		final ClientResponse response = resource.type(MIMETypes.APPLICATION_JSON.getName()).post(
				ClientResponse.class, gson.toJson(FantaserviceApp.request));
		if (response.getStatus() != 201 && response.getStatus() != 200) {
			final String respCode = ""+ response.getStatus();
			throw new ConnectionException(respCode);
		}
		final String responseEntity = response.getEntity(String.class).replaceAll("\\\\", "");
		utenti = mapper.readValue(responseEntity, Utente[].class);
		
		if(utenti != null && (utenti[0] != null && !"".equals(utenti[0].getUserid()) && utenti[0].getUserid() != null)){
			FantaserviceApp.utente = utenti[0];
			retVal = !"".equals(FantaserviceApp.utente.getNome());
			FantaserviceApp.utente.setPassword(FantaserviceApp.request.getPassword());
			FantaserviceApp.leghe = new ArrayList<LegaSquadra>();
			final WebResource resource2 = client.resource(Constants.URL_REST + Constants.SERVICE_LEGA);
			
			LegaSquadra[] legaPrivata = null;
			//App.request.setIdlega(App.utente.getIdlegaprivata());
			final ClientResponse response2 = resource2.type(MIMETypes.APPLICATION_JSON.getName()).post(
					ClientResponse.class, gson.toJson(FantaserviceApp.request));
			
			
			String responseEntity2 = response2.getEntity(String.class).replaceAll("\\\\", "");///"(\w+)"\s*:/g, '$1:');
//			responseEntity2 = responseEntity2.replaceAll("\"", "");
			String responseNormalized = normalizeResponse(responseEntity2);
//			mapper.configure(JsonParser.Feature., true); 
			legaPrivata = mapper.readValue(responseNormalized, LegaSquadra[].class);
			if(legaPrivata!= null){
				for(int i=0 ; i< legaPrivata.length; i++){
					FantaserviceApp.leghe.add(legaPrivata[i]);
				}
				isLegaPresent = true;
			}
				
			if(rimaniConnesso && retVal){
				SharedPreferences pref = context.getSharedPreferences(Constants.PREFS_NAME,Activity.MODE_PRIVATE); 
				 pref.edit().putString(Constants.PREF_USERNAME, FantaserviceApp.request.getUsername()).putString(Constants.PREF_PASSWORD, FantaserviceApp.request.getPassword()).commit();
				 requestBackup() ;
			}
			
			
		}else{
//			meinActivityWeakRef.get().runOnUiThread(new Runnable(){
//	            public void run() {
//	            	new GenericDialog(meinActivityWeakRef.get(), "Login Errato",Constants.TITLE_ERROR);
//	            	App.utente = null;
//	                  }
//	    	});
			FantaserviceApp.utente = null;
			
		}
			
		
		return retVal;
	}

	/**
	 * 
	 * 	 * @param MY_PATTERN
	 * @param response
	 * @return
	 */
	public String normalizeResponse(String response) {
		Pattern MY_PATTERN = Pattern.compile("\\{(.*?)\\}");
		Matcher m = MY_PATTERN.matcher(response);
		StringBuffer newResponse = new StringBuffer();
		newResponse.append("[");
		int i=0;
		while (m.find()) {
			if(i>0){
				newResponse.append(",");
			}
		    String sngleResponse = m.group(1);
		    
			MY_PATTERN = Pattern.compile("\"nome\":(.*?),");
			Matcher m1 = MY_PATTERN.matcher(sngleResponse);
			String nome="";
			while (m1.find()) {
			    String s = m1.group(1);
			    nome = s.replace("\"", "");
			}
			String nomeString = sngleResponse.replaceAll("\"nome\":(.*?),", "\"nome\":\""+nome+"\",");
			MY_PATTERN = Pattern.compile("\"nomesquadra\":(.*?),");
			m1 = MY_PATTERN.matcher(nomeString);
			String nomeSquadra="";
			while (m1.find()) {
			    String s = m1.group(1);
			    nomeSquadra = s.replace("\"", "");
			}
			String nomeSquadraString = nomeString.replaceAll("\"nomesquadra\":(.*?),", "\"nomesquadra\": \""+nomeSquadra+"\",");
	
			MY_PATTERN = Pattern.compile("\"supporters\":(.*?),");
			m1 = MY_PATTERN.matcher(nomeSquadraString);
			String supporters="";
			while (m1.find()) {
			    String s = m1.group(1);
			    supporters = s.replace("\"", "");
			}
			String supportersString = nomeSquadraString.replaceAll("\"supporters\":(.*?),", "\"supporters\":\""+supporters+"\",");
	
			MY_PATTERN = Pattern.compile("\"presidente\":(.*?),");
			m1 = MY_PATTERN.matcher(supportersString);
			String presidente="";
			while (m1.find()) {
			    String s = m1.group(1);
			    presidente = s.replace("\"", "");
			}
			String presidenteString = supportersString.replaceAll("\"presidente\":(.*?),", "\"presidente\":\""+presidente+"\",");
			
			MY_PATTERN = Pattern.compile("\"arena\":(.*?),");
			m1 = MY_PATTERN.matcher(presidenteString);
			String arena="";
			while (m1.find()) {
			    String s = m1.group(1);
			    arena = s.replace("\"", "");
			}
			String arenaString = presidenteString.replaceAll("\"arena\":(.*?),", "\"arena\":\""+arena+"\",");
			
			newResponse.append("{" + arenaString + "}");
			
			i++;
		}
//		newResponse = new StringBuffer(newResponse.substring(0, newResponse.length() -1 ));
		newResponse.append("]");
		return newResponse.toString();
	}
	
	public void requestBackup() {
	   BackupManager bm = new BackupManager(meinActivityWeakRef.get());
	   bm.dataChanged();
	 }
}
